﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Net;

namespace Documents.Common.Helpers
{
    public static class XmlHelper
    {
        /// <summary>
        /// Transforms a XML document to xHtml using the supplied xslt transformation 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="transformSource"></param>
        /// <returns></returns>
        public static string TransformXML(XmlDocument source, string transformSource)
        {
            if (source.InnerText == string.Empty)
                return string.Empty;
            string xHtml;
            XmlWriterSettings xmlwritersettings = new XmlWriterSettings();
            xmlwritersettings.OmitXmlDeclaration = true;
            xmlwritersettings.ConformanceLevel = ConformanceLevel.Fragment;
            xmlwritersettings.CloseOutput = false;
            using (System.IO.StringReader sReader = new System.IO.StringReader(source.InnerXml))
            using (System.Xml.XmlReader xReader = System.Xml.XmlReader.Create(sReader))
            using (System.IO.StringWriter sWriter = new System.IO.StringWriter())
            using (System.Xml.XmlWriter xWriter = System.Xml.XmlWriter.Create(sWriter, xmlwritersettings))
            {
                System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
                xslt.Load(transformSource);
                xslt.Transform(xReader, xWriter);
                xHtml = sWriter.ToString();
             }
            return xHtml;
        }

        public static XmlNode Serialize(object o)
        {
            // Serialize the object to XML
            var xmlSerialiser = new XmlSerializer(o.GetType());
            var ms = new MemoryStream();
            xmlSerialiser.Serialize(ms, o);
            ms.Position = 0;
            var document = new XmlDocument();
            document.Load(ms);
            return document.ChildNodes[1];
        }


        public static XmlDocument Serialize(object o, string listTitle, string containerName)
        {
            XmlDocument result = new XmlDocument();
            XmlNode container = containerName == null ?  null :  result.CreateNode(XmlNodeType.Element, "", containerName, "");
            if (o != null)
            {
                XmlNode node = XmlHelper.Serialize(o);
                if (container != null)
                    container.InnerXml = node.InnerXml;
                else
                    result.LoadXml(node.OuterXml);

            }
            if (!string.IsNullOrEmpty(listTitle))
            {
                XmlNode titlenode = result.CreateNode(XmlNodeType.Element, "", "ListTitle", "");
                titlenode.InnerText = listTitle;
                if (container != null)
                    container.AppendChild(titlenode);
                else
                    result.AppendChild(titlenode);
            }
            if (container != null)
                result.AppendChild(container);
            return result;
        }

        public static XmlDocument Get(string url)
        {
            XmlDocument result = new XmlDocument();
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            HttpWebResponse response = req.GetResponse() as HttpWebResponse;
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string xml = sr.ReadToEnd();
            sr.Close();
            result.LoadXml(xml);
            return result;
        }

        public static XmlDocument Post(string url, string postData)
        {
            XmlDocument result = new XmlDocument();
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.Method = "POST";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = byteArray.Length;
            req.ContentType = "application/x-www-form-urlencoded";
            Stream dataStream = req.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            HttpWebResponse response = req.GetResponse() as HttpWebResponse;
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string xml = sr.ReadToEnd();
            sr.Close();
            result.LoadXml(xml);
            return result;
        }
    }
}
